<%--
  Created by IntelliJ IDEA.
  User: 陌·笙
  Date: 2018-12-10
  Time: 9:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <jsp:include page="../comm/tag.jsp"></jsp:include>
    <script>
        $(function(){
            $("#mytable").bootstrapTable({
                url:"/role/showRole",
                height:600,
                pageSize:7,
                pageNumber:1,
                pageList:[2,4,8,16],
                //启用分页，但是默认情况下，是客户端分页的
                pagination:true,
                sidePagination:'server',
                queryParams:function(params){
                    var temp = {  //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                        limit: params.limit,  //页面大小
                        offset: params.offset, //页码
                        roleName:$("[name='roleName']").val(),
                        positionId:$("[name='op']").val()
                    };
                    return temp;
                },
                locale:'zh-CN',//中文支持,
                toolbar:'#top',
                columns:[
                    {
                        checkbox:true
                    },
                    {
                        field:"aid",
                        title:"用户编号",
                        align:"center"
                    },
                    {
                        title:"用户头像",
                        align:"center",
                        formatter:function (value,row,index) {
                            return "<img alt=\"image\" class=\"img-circle\" src='"+row.photo+"' width=\"50\" height=\"50\" />"
                        }
                    },
                    {
                        field:"aname",
                        title:"用户名称",
                        align:"center"
                    },
                    {
                        field:"telephone",
                        title:"用户电话",
                        align:"center"
                    },
                    {
                        field:"aremark",
                        title:"用户备注",
                        align:"center"
                    },
                    {
                        field:"position.positionName",
                        title:"用户职位",
                        align:"center"
                    },
                    {
                        title:"分配权限",
                        align:"center",
                        formatter:function (value,row,index) {
                            return "<button class='btn btn-primary' onclick='trss(\""+row.aid+"\")'><span class='glyphicon glyphicon-edit'></span>&nbsp; 权限</button>"
                        }
                    },
                    {
                        title:"操作",
                        align:"center",
                        formatter:function (value,row,index) {
                            return "<a onclick='ups(("+index+"))'>&nbsp;修改</a>"
                        }
                    }
                ]
            });

            $.ajax({
                url:"/role/showPosition",
                type:"get",
                success:function(data){
                    $.each(data,function(){
                        var adds=$("<option value='"+this.positionId+"'>"+this.positionName+"</option>");
                        $(".k").append(adds);
                    });
                }
            })
        })
        function ups(index){//修改
            $("#mytable").bootstrapTable("check",index);//根据索引让该行选中
            var a=$("#mytable").bootstrapTable("getSelections")[0];
            $("#xiugai").modal('show');
            $(".aname").val(a.aname);
            $(".apwd").val(a.apwd);
            $(".pwds").val(a.apwd);
            $(".aremark").val(a.aremark);
            $(".aid").val(a.aid);
            $(".telephone").val(a.telephone);
            $("#op").val(a.positionId);
            $(".tablesId").val(index);
        }
      function  cha(){//查询
          var opts = $("#mytable").bootstrapTable("getOptions") ;
            var roleName=$("[name='roleName']").val();
            var positionName=$("[name='op']").val();
          var limit = opts.pageSize ;
          var offset = (opts.pageNumber-1) * limit;
            $.ajax({
                url:"/role/showRole",
                type:"get",
                data:{"roleName":roleName,"positionId":positionName,'limit':limit,'offset':offset},
                success:function(data){
                    $("#mytable").bootstrapTable("load",data);
                }
            })
        }
        function todel() {//删除
            var ids = "" ;//一个字符串
            var rows = $("#mytable").bootstrapTable("getSelections") ;
            if (rows.length==0){
                swal("错误！", "请选择要删除的数据！", "error");
            }
            else{
                $.each(rows,function (index,row) {
                    ids = ids + row.aid + "," ;
                    $.ajax({
                        type:"post",
                        url:"/role/deluser",
                        data:{"id":ids},
                        success:function(data){
                            $("#mytable").bootstrapTable("load",data);
                        }
                    })
                })

            }
        }
       $(function(){//上传头像
           $(".myfile").fileinput({
               language: 'zh',
               uploadUrl: "/role/uploadFile",
               maxFileSize: 0, //文件的大小
               maxFileCount:1,//文件的数量
               showUpload:true, //是否显示上传按钮
               showRemove :false, //显示移除按钮
               showPreview :true, //是否显示预览
               allowedFileExtensions: ["jpg", "png", "gif","jpeg"],
               enctype: 'multipart/form-data', //二进制传递参数
               browseClass: "btn btn-primary", //按钮样式
               dropZoneEnabled : false,//是否显示拖拽区域，默认不写为true，但是会占用很大区域
               previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
               msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
           }).on("fileuploaded", function (event, data, previewId, index){
               swal({title:"上传成功",text:"小手一抖就上传成功了！",type:"success"});
               $("[name='photo']").val("/image/"+data.response.url);
           });
       })
        $(function () {//添加框
            <!--校验框架-->
            $('#myform').bootstrapValidator({
                message: 'This value is not valid',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    aname: {
                        message: 'The username is not valid',
                        validators: {
                            notEmpty: {
                                message: '用户名不能为空！'
                            },
                            stringLength: {
                                min: 2,
                                max: 4,
                                message: '必须是2-4个字符'
                            }
                        }
                    },
                    apwd: {
                        message: '',
                        validators: {
                            notEmpty: {
                                message: '密码不能为空！'
                            }
                        }
                    },
                    pwds: {
                        message: '',
                        validators: {
                            notEmpty: {
                                message: '确认密码不能为空！'
                            },
                            identical: {
                                field: 'apwd',
                                message: '两次密码不一致'
                            }
                        }

                    },
                    telephone: {
                        validators: {
                            notEmpty: {
                                message: '手机号码不能为空！'
                            },
                            regexp: {
                                regexp: /^(13[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(17[0-9]{9})|(15[0-9]{9})$/,
                                message: '请填写正确的手机号码'
                            }
                        }

                    },
                    aremark:{
                        validators: {
                            stringLength: {
                                min: 0,
                                max: 15,
                                message: '必须是0-15个字符'
                            }
                        }
                    },
                    myfile: {
                        validators: {
                            notEmpty: {
                                message: '头像不能为空'
                            },
                            file: {
                                extension: 'png,jpg,jpeg,gif',
                                message: '请重新选择图片'
                            }
                        }
                    },
                    photo: {
                        validators: {
                            notEmpty: {
                                message: '请先上传头像'
                            },
                        }
                    }
                }
            })
        })
        $(function () {//修改框
            <!--校验框架-->
            $('#myforms').bootstrapValidator({
                message: 'This value is not valid',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    aname: {
                        message: 'The username is not valid',
                        validators: {
                            notEmpty: {
                                message: '用户名不能为空！'
                            },
                            stringLength: {
                                min: 2,
                                max: 4,
                                message: '必须是2-4个字符'
                            }
                        }
                    },
                    apwd: {
                        message: '',
                        validators: {
                            notEmpty: {
                                message: '密码不能为空！'
                            }
                        }
                    },
                    pwds: {
                        message: '',
                        validators: {
                            notEmpty: {
                                message: '确认密码不能为空！'
                            },
                            identical: {
                                field: 'apwd',
                                message: '两次密码不一致'
                            }
                        }

                    },
                    telephone: {
                        validators: {
                            notEmpty: {
                                message: '手机号码不能为空！'
                            },
                            regexp: {
                                regexp: /^(13[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(17[0-9]{9})|(15[0-9]{9})$/,
                                message: '请填写正确的手机号码'
                            }
                        }

                    },
                    aremark:{
                        validators: {
                            stringLength: {
                                min: 0,
                                max: 15,
                                message: '必须是0-15个字符'
                            }
                        }
                    }
                }
            })
        })
        function smt() {//添加
            //启用较验
            $('#myform').data('bootstrapValidator').validate();
            //验证是否通过true/false
            var flag = $('#myform').data('bootstrapValidator').isValid();
            if (flag) {
                //序列化表单
                var formStr = $('#myform').serialize();
                //处理表单控件的中文乱码
                admin = decodeURIComponent(formStr, true);
                $.ajax({
                    'type': 'post',
                    'url': '/role/adduser',
                    'data':admin,
                    success: function (data) {
                        //关闭对话框
                        $("#modal-id").modal('hide');
                        swal({title:"添加成功",text:"小手一抖就添加成功了！",type:"success"});
                        //重新加载表格
                        $("#mytable").bootstrapTable('load', data);
                        $('#myform')[0].reset();
                        $('#myform').data('bootstrapValidator').resetForm();
                    }
                })
            }
        }
        function up() {//修改
            //启用较验
            $('#myforms').data('bootstrapValidator').validate();
            //验证是否通过true/false
            var flag = $('#myforms').data('bootstrapValidator').isValid();
            if (flag) {
                //序列化表单
                var formStr = $('#myforms').serialize();
                //处理表单控件的中文乱码
                admin = decodeURIComponent(formStr, true);
                $.ajax({
                    'type': 'post',
                    'url': '/role/upuser',
                    'data':admin,
                    success: function (data) {
                        //关闭对话框
                        $("#xiugai").modal('hide');
                        swal({title:"修改成功",text:"小手一抖就修改成功了！",type:"success"});
                        //重新加载表格
                        $("#mytable").bootstrapTable('load', data);
                        $('#myforms')[0].reset();
                        $('#myforms').data('bootstrapValidator').resetForm();
                        $("#mytable").bootstrapTable("uncheck",$(".tablesId").val());//取消
                    }
                })
            }
        }
       $(function(){//关闭所有的模态框
           $(".closes").on("click",function () {
               //关闭对话框
               $("#modal-id").modal('hide');
               $("#xiugai").modal('hide');
               //清空表单
               $('#myform')[0].reset();
               $('#myforms')[0].reset();
               //清空校验
               $('#myform').data('bootstrapValidator').resetForm();
               $('#myforms').data('bootstrapValidator').resetForm();
               $("#mytable").bootstrapTable("uncheck",$(".tablesId").val());//取消
           })

       });
        function fenpei(){
            var roleId = "";
            //1.
            var cks = $("#tree").treeview('getChecked') ;
            $.each(cks,function (i,n) {
                //2.
                roleId = roleId + "-" + n.id;
            })
            $.post('/role/addtreeBean',{'aids':aids,'roleId':roleId},function (data) {

                if (data.msg=="1" ){
                    //关闭对话框
                    $("#trees").modal('hide');
                }

            })
        }
    </script>
</head>
<body>
<div style="margin-left: 50px;margin-right: 50px">
    <div class="#top" style="margin-top: 30px">
       <div class="col-md-3">
           <a class="btn btn-primary" data-toggle="modal" href="#modal-id"><span class="glyphicon glyphicon-plus"></span>添加</a>
           <button onclick="todel()" class="btn btn-primary"><span class="glyphicon glyphicon-trash"></span>&nbsp;&nbsp;删除</button>
       </div>
        <div class="col-md-9">
            <form action="" method="post" role="form" class="form-horizontal" enctype="multipart/form-data">
                <div class="form-group col-md-4">
                    <label for="" class="col-md-4 control-label">用户名:</label>
                   <div class="col-md-8">
                       <input type="text" class="form-control" name="roleName" placeholder="可模糊查询">
                   </div>
                </div>
                <div class="form-group col-md-4">
                    <label for="" class="col-md-4 control-label">职位:</label>
                    <div class="col-md-8">
                        <select name="op" id="inputID" class="form-control k">
                            <option value="0">全部</option>
                        </select>
                    </div>
                </div>
                <button type="button" class="btn btn-primary btn-info glyphicon glyphicon-search" onclick="cha()">查询</button>
            </form>
        </div><%--搜索框--%>
    </div>
    <div class="modal fade" id="modal-id">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close closes" aria-hidden="true">&times;</button>
                    <h4 class="modal-title">添加管理员</h4>
                </div>
                <div class="modal-body">
                    <form action="" id="myform" method="post" role="form" class="form-horizontal">
                        <div class="form-group">
                            <label for="" class="col-md-2  control-label">用户名:</label>
                            <div class="col-md-10">
                            <input type="text" class="form-control" name="aname"placeholder="请输入用户名">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="" class="col-md-2  control-label">密码:</label>
                            <div class="col-md-10">
                            <input type="password" class="form-control" name="apwd"placeholder="请输入密码">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="" class="col-md-2  control-label">确认密码:</label>
                            <div class="col-md-10">
                                <input type="password" class="form-control" name="pwds"placeholder="请输入密码">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="" class="col-md-2  control-label">电话号码:</label>
                            <div class="col-md-10">
                            <input type="text" class="form-control" name="telephone"placeholder="请输入电话号码">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="" class="col-md-2  control-label">头像:</label>
                            <div class="col-md-10">
                                <input multiple type="file" name="myfile" class="myfile" value="" />
                                <input type="hidden" class="form-control" name="photo">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="" class="col-md-2  control-label">职位:</label>
                            <div class="col-md-10">
                                <select name="positionId" class="form-control k">
                                </select>
                            </div>
                            </div>
                        <div class="form-group">
                            <label for="" class="col-md-2  control-label">备注信息:</label>
                            <div class="col-md-10">
                                <input type="text" class="form-control" name="aremark"placeholder="请输入备注">
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default closes">取消</button>
                    <button type="button" class="btn btn-primary" onclick="smt()">保存</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.添加 -->
    <div class="modal fade" id="xiugai">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close closes"  aria-hidden="true">×</button>
                    <h4 class="modal-title">修改管理员</h4>
                </div>
                <div class="modal-body">
                    <form action="" id="myforms" method="post" role="form" class="form-horizontal">
                        <div class="form-group">
                            <label for="" class="col-md-2  control-label">用户名:</label>
                            <div class="col-md-10">
                                <input type="text" class="form-control aname" name="aname"placeholder="请输入用户名">
                                <input type="hidden" class="form-control aid" name="aid">
                                <input type="hidden" class="form-control tablesId" name="tablesId">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="" class="col-md-2  control-label">密码:</label>
                            <div class="col-md-10">
                                <input type="password" class="form-control apwd" name="apwd"placeholder="请输入密码">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="" class="col-md-2  control-label">确认密码:</label>
                            <div class="col-md-10">
                                <input type="password" class="form-control pwds" name="pwds"placeholder="请输入密码">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="" class="col-md-2  control-label">电话号码:</label>
                            <div class="col-md-10">
                                <input type="text" class="form-control telephone" name="telephone"placeholder="请输入电话号码">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="" class="col-md-2  control-label">备注信息:</label>
                            <div class="col-md-10">
                                <input type="text" class="form-control aremark" name="aremark"placeholder="请输入备注">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="" class="col-md-2  control-label">职位:</label>
                            <div class="col-md-10">
                                <select name="positionId" class="form-control k" id="op">
                                </select>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default closes">取消</button>
                    <button type="button" class="btn btn-primary" onclick="up()">保存</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.修改 -->
    <div class="modal fade" id="trees">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title">权限管理</h4>
                </div>
                <div class="modal-body">
                    <div id="tree"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="fenpei()">保存</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.权限 -->
    <table id="mytable" class="table-striped"></table><%--数据展示--%>
</div>
<script>
    var aids;
    function trss(aid){//显示权限模态框
        $("#trees").modal('show');
        var a =0 ;
        aids=aid;
        $("#trees").on("shown.bs.modal",function(){
            if (++a ==1){
            $.post("${pageContext.request.contextPath}/role/treeBean",{'aid':aid},function (data) {
                $('#tree').treeview({
                    showCheckbox: true,
                    data:data,
                    onNodeChecked: nodeChecked,
                    onNodeUnchecked: nodeUnchecked
                });
            });
            }
        })
    }
    var nodeCheckedSilent = false;

    function nodeChecked(event, node) {
        if (nodeCheckedSilent) {
            return;
        }
        nodeCheckedSilent = true;
        checkAllParent(node);
        checkAllSon(node);
        nodeCheckedSilent = false;
    }

    var nodeUncheckedSilent = false;

    function nodeUnchecked(event, node) {
        if (nodeUncheckedSilent)
            return;
        nodeUncheckedSilent = true;
        uncheckAllParent(node);
        uncheckAllSon(node);
        nodeUncheckedSilent = false;
    }

    //选中全部父节点
    function checkAllParent(node) {
        $('#tree').treeview('checkNode', node.nodeId, {
            silent: true
        });
        var parentNode = $('#tree').treeview('getParent', node.nodeId);
        if (!("nodeId" in parentNode)) {
            return;
        } else {
            checkAllParent(parentNode);
        }
    }
    //取消全部父节点
    function uncheckAllParent(node) {
        $('#tree').treeview('uncheckNode', node.nodeId, {
            silent: true
        });
        var siblings = $('#tree').treeview('getSiblings', node.nodeId);
        var parentNode = $('#tree').treeview('getParent', node.nodeId);
        if (!("nodeId" in parentNode)) {
            return;
        }
        var isAllUnchecked = true; //是否全部没选中
        for (var i in siblings) {
            if (siblings[i].state.checked) {
                isAllUnchecked = false;
                break;
            }
        }
        if (isAllUnchecked) {
            uncheckAllParent(parentNode);
        }

    }

    //级联选中所有子节点
    function checkAllSon(node) {
        $('#tree').treeview('checkNode', node.nodeId, {
            silent: true
        });
        if (node.nodes != null && node.nodes.length > 0) {
            for (var i in node.nodes) {
                checkAllSon(node.nodes[i]);
            }
        }
    }
    //级联取消所有子节点
    function uncheckAllSon(node) {
        $('#tree').treeview('uncheckNode', node.nodeId, {
            silent: true
        });
        if (node.nodes != null && node.nodes.length > 0) {
            for (var i in node.nodes) {
                uncheckAllSon(node.nodes[i]);
            }
        }
    }
</script>
</body>
</html>
